﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Business.Solr {
    public class SolrResponseFacet {
        [JsonProperty("facet_fields")]
        public IDictionary<string, object[]> RawFacetFields {
            get;
            set;
        }

        [JsonProperty("facet_queries")]
        public IDictionary<string, int> FacetQueries {
            get;
            set;
        }

        [JsonIgnore]
        public IDictionary<string, Dictionary<string, int>> FacetFields {
            get {
                if(RawFacetFields == null)
                    return null;
                return RawFacetFields.ToDictionary(kvp => kvp.Key,
                    kvp => {
                        // 将kvp.Value数据中的一个元素转换成facet的key，下一个元素转换成facet的value
                        return SplitArray(kvp.Value).ToDictionary(p => p.Key, p => p.Value);
                    });
            }
        }

        private IEnumerable<KeyValuePair<string, int>> SplitArray(object[] array) {
            if(array == null)
                yield break;
            for(var i = 0; i < array.Length - 1; i += 2) {
                if(array[i] != null && array[i + 1] != null &&
                    array[i].GetType() == typeof(string) &&
                    (array[i + 1].GetType() == typeof(long) || array[i + 1].GetType() == typeof(int))) {
                    var key = (string)array[i];
                    var value = Convert.ToInt32(array[i + 1]);
                    yield return new KeyValuePair<string, int>(key, value);
                }
            }
        }
    }
}
